package com.hk.aefz.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hk.aefz.po.Account;
import com.hk.aefz.service.AccountService;
import com.hk.aefz.shiro.Md5;
import com.hk.aefz.utils.VerifyUtil;
import com.hk.aefz.vo.ResultMsg;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.apache.ibatis.annotations.Results;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;

/**
 * <p>
 * 账户表 前端控制器
 * </p>
 *
 * @author 阿尔法哲
 * @since 2020-07-21
 */
@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @Autowired
    private VerifyUtil verifyUtil;
//    验证码
    private String yzmm;

    @ApiOperation("生成验证码")
    @GetMapping(path = "/getcode")
    public void getCode(HttpServletResponse response , HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
//        使用图片工具生成图片
        //第一个参数是生成的验证码，第二个参数是生成的图片
        Object[] objs = verifyUtil.createImage();
//       将验证码存入Session
        session.setAttribute("imagecode",objs[0]);
        //        获取验证码
        yzmm = (String)session.getAttribute("imagecode");
//        将图片输出给浏览器
        BufferedImage image = (BufferedImage) objs[1];
        response.setContentType("image/png");
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image,"png",outputStream);
    }

    /**
     * 注册
     * @param aaccount
     * @param aemail
     * @param apassword
     */
    @PostMapping(path = "/register")
    public ResultMsg register(
            @RequestParam String  aaccount,
            @RequestParam String aemail,
            @RequestParam String apassword,
            @RequestParam String yzm) {
//        密码盐值加密
        String password = new Md5().md5yz(apassword, aaccount);
        ResultMsg resultMsg = accountService.saveAccount(aaccount,aemail,password,yzm,yzmm);
        return  resultMsg;
    }

    @PostMapping(path = "/login")
    public ResultMsg login(
            @RequestParam(value = "aaccount")String username,
            @RequestParam(value = "apassword")String pwd,
            @RequestParam("check") Integer check,
            @RequestParam String yzm) {
        ResultMsg resultMsg = new ResultMsg();
        if (yzm == null || !yzm.equals(yzmm.toLowerCase())) {
            resultMsg.setState(412);
            resultMsg.setMsg("验证码输入错误！");
            return resultMsg;
        }
        //        获取当前用户
        Subject subject = SecurityUtils.getSubject();
        /**
         * 判断当前用户是否已经认证过
         */
//        System.out.println("是否记住我==="+subject.isRemembered());
        if (!subject.isAuthenticated()) {
    //            封装用户的登录数据
            UsernamePasswordToken token = new UsernamePasswordToken(username,pwd);
            Boolean rememberMe = check == 1 ? true:false;
            token.setRememberMe(rememberMe); //记住我
            try {
                subject.login(token); //登录认证
                resultMsg.setState(200);
                resultMsg.setMsg("登录成功");
                return resultMsg;
            } catch (UnknownAccountException u) {
                System.err.println("用户不存在");
                resultMsg.setState(412);
                resultMsg.setMsg("用户不存在");
                return resultMsg;
            } catch (IncorrectCredentialsException i) {
                System.err.println("密码错误");
                resultMsg.setState(412);
                resultMsg.setMsg("密码错误");
                return resultMsg;
            } catch (LockedAccountException l) {
                System.err.println("账户锁定");
                resultMsg.setState(412);
                resultMsg.setMsg("账户锁定");
                return resultMsg;
            }
        } else {
            resultMsg.setState(403);
            resultMsg.setMsg("此账户已在其他地方登录,是否强制下线?");
            return resultMsg;
        }

    }

    /**
     * 查询登录账户信息
     * @param username
     * @return
     */
    @GetMapping(path = "/selectByName")
    public Account selectByName(String username) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("aaccount",username);
        Account account = accountService.getOne(queryWrapper);
        return account;
    }

    /**
     * 退出登录
     * @param num
     * @return
     */
    @GetMapping(path = "/loginout")
    public ResultMsg loginOut(Integer num) {
        ResultMsg resultMsg = new ResultMsg();
//        获取当前用户
        Subject subject = SecurityUtils.getSubject();
        subject.logout();//退出当前登录
        resultMsg.setState(200);
        if (num == 1) {
            resultMsg.setMsg("已下线!");
        } else {
            resultMsg.setMsg("当前用户已退出!");
        }
        return resultMsg;

    }

}

